package android.twitter.clientroid;

import twitter4j.Twitter;
import twitter4j.TwitterException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SendTweetActivity extends Activity
{
	protected static final int tweetLength = 140;
	private EditText tvTweet;
	private Button submitTweet;
	SharedPreferences settings;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tweetpage);
        
        final TextView tvChar = (TextView) this.findViewById(R.id.tvChar);
        tvTweet = (EditText) this.findViewById(R.id.tb_tweet);
        
        tvTweet.setOnKeyListener(
        		new View.OnKeyListener() {
        			
    				@Override
    				public boolean onKey(View v, int keyCode, KeyEvent event) {
    					// TODO Auto-generated method stub
    					Integer length = tweetLength - tvTweet.getText().length();
    					tvChar.setText(length.toString());
    					return false;
    				}
    			});
        
        submitTweet = (Button) this.findViewById(R.id.btn_tweet);
        submitTweet.setOnClickListener(
    		new View.OnClickListener()
    		{
    			@Override
    			public void onClick(View v)
    			{
    				String status = tvTweet.getText().toString();
    				if(status.length() == 0)
    				{
    					Toast.makeText(SendTweetActivity.this, "please write a tweet", Toast.LENGTH_LONG).show();
    					return;
    				}
    				
					SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
					String accessTokenToken = settings.getString("accessTokenToken", null);
					String accessTokenSecret = settings.getString("accessTokenSecret", null);
					if(accessTokenToken == null || accessTokenSecret == null)
					{
						//access token is null
						Toast.makeText(SendTweetActivity.this, "please relogin", Toast.LENGTH_LONG).show();
						Intent loginIntent = new Intent(SendTweetActivity.this, LoginActivity.class);
						startActivity(loginIntent);
					}
					else
					{
						//access token exists
						Toast.makeText(SendTweetActivity.this, "sending ...", Toast.LENGTH_LONG).show();
						Twitter preAuthorizedTwitter = ((TwitterApplication)getApplication()).getTwitter();
						
						try
						{
							preAuthorizedTwitter.updateStatus(status);
						}
						catch (TwitterException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Intent returnIntent = new Intent(SendTweetActivity.this, TimeLineActivity.class);
						startActivity(returnIntent);
					}

    			}
    		});
        
    }
    
}